<template>
    <section class="freight-dialog">
        <el-dialog title="选择可配送区域"
                   width="60%"
                   :show-close='false'
                   show-checkbox
                   :visible.sync="freightDialogVisible">
            <div class="freight-dialog-content" v-loading="loading">
                <div class="fy-tree" v-if="freightDialogVisible">
                    <div class="fy-tree_nav">
                        可选省、市、区
                    </div>
                    <div class="fy-tree_content">
                        <el-tree
                                node-key="id"
                                accordion
                                ref="tree"
                                show-checkbox
                                :load="loadProvinces"
                                lazy>
                            <span slot-scope="{ node, data }">
                                <span>{{ data.text }}</span>
                            </span>
                        </el-tree>
                    </div>
                </div>
                <el-button style="margin: 0 20px" @click="addTree()">添加</el-button>
                <div class="fy-tree">
                    <div class="fy-tree_nav">
                        已选省、市、区
                    </div>
                    <div class="fy-tree_content">
                        <el-tree
                                :data="treeData"
                                node-key="id"
                                accordion>
                          <span slot-scope="{ node, data }">
                              <span>{{ data.text }}</span>
                              <el-button
                                      type="text"
                                      size="mini"
                                      @click="() => remove(node, data)">
                                删除
                              </el-button>
                          </span>
                        </el-tree>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="submit" type="primary">确定</el-button>
                <el-button @click="freightDialogVisible = false">取 消</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    export default {
        // 全局感知
        name: "FreightDialog",

        // 模板依赖
        components: {},
        filters: {},

        // 接口
        props: {},

        // 本地状态
        data() {
            return {
                freightDialogVisible: false,
                loading: false,
                type: 'add',
                index: -1,
                freightData: [],
                treeData: []
            };
        },
        computed: {},

        // 事件
        watch: {},
        beforeCreate() {
        },
        created() {
        },
        beforeMount() {
        },
        mounted() {
        },
        beforeUpdate() {
        },
        updated() {
        },
        beforeDestroy() {
        },
        destroyed() {
        },

        // 非响应式的属性
        methods: {
            initData() {
            },
            showDialog(type, data, index) {
                this.type = type;
                this.index = index;
                this.initTreeData(data);
                this.freightDialogVisible = true;
            },
            submit() {
                let list = [];
                const addList = (data)=>{
                    list.push(...data);
                    let childrenList = [];
                    data.map(item=> {
                        childrenList.push(...item.children);
                    });
                    if(childrenList.length){
                        addList(childrenList);
                    }else {
                        this.$emit('freightDialog', this.type, list, this.index);
                    }
                };
                addList(this.treeData);
                this.freightDialogVisible = false;
            },
            initTreeData(data) {
                this.treeData = [];
                this.freightData = [];
                this.setFreightData(data);
                this.setTreeData();
            },
            loadProvinces(node, resolve) {
                if (node.level === 0) {
                    axios
                        .get('provinces', {
                            params: {
                                pagination: 1,
                                pageSize: 9999,
                                pid: 0,
                                sortBy: 'id',
                                orderBy: 'asc',
                            }
                        })
                        .then(res => res.data.data)
                        .then(res => {
                            return resolve(res || []);
                        })
                } else if (node.level > 0 && node.level < 3) {
                    axios
                        .get('provinces', {
                            params: {
                                pagination: 1,
                                pageSize: 9999,
                                pid: node.data.id,
                                sortBy: 'id',
                                orderBy: 'asc',
                            }
                        })
                        .then(res => res.data.data)
                        .then(res => {
                            if(res.level === 3){
                                res.children = [];
                            }
                            return resolve(res || []);
                        })
                }else {
                    return resolve([]);
                }
            },
            remove(node, data) {
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex(d => d.id === data.id);
                children.splice(index, 1);
                this.freightData = JSON.parse(JSON.stringify(this.treeData))
            },
            addTree() {
                this.loading = true;
                if (this.$refs.tree.getHalfCheckedKeys().length){
                    this.getHalfCheckedKeysProvinces();
                }else if(this.$refs.tree.getCheckedKeys().length){
                    this.getCheckedKeysProvinces();
                } else {
                    this.setTreeData();
                }
            },
            getHalfCheckedKeysProvinces() {
                axios
                    .get('provinces', {
                        params: {
                            pagination: 1,
                            pageSize: 9999,
                            id: ['in', this.$refs.tree.getHalfCheckedKeys().toString()],
                            sortBy: 'id',
                            orderBy: 'asc',
                        }
                    })
                    .then(res => res.data.data)
                    .then(res => {
                        res.map( item => {
                            item.children = [];
                            if(item.level === 1){
                                this.compareFreight(this.freightData, item.id) ? this.freightData.push(item): console.log();
                            } else if(item.level === 2){
                                this.freightData.forEach(freightData => {
                                    if (freightData.id === item.pid) {
                                        this.compareFreight(freightData.children, item.id) ? freightData.children.push(item) : console.log();
                                    }
                                })
                            }
                        });
                        return this.freightData;
                    }).then(freightData => {
                        this.getCheckedKeysProvinces();
                    });
            },
            getCheckedKeysProvinces() {
                axios
                    .get('provinces', {
                        params: {
                            pagination: 1,
                            pageSize: 9999,
                            id: ['in', this.$refs.tree.getCheckedKeys().toString()],
                            sortBy: 'id',
                            orderBy: 'asc',
                        }
                    })
                    .then(res => res.data.data)
                    .then(res => {
                        let getCheckedKeysSet = new Set(this.$refs.tree.getCheckedKeys());
                        for (let item of res){
                            item.children = [];
                            if(item.level === 1){
                                this.compareFreight(this.freightData, item.id) ? this.freightData.push(item): console.log();
                            } else if(item.level === 2){
                                this.freightData.forEach(freightData => {
                                    if (freightData.id === item.pid) {
                                        getCheckedKeysSet.delete(freightData.id);
                                        this.compareFreight(freightData.children, item.id) ?
                                            freightData.children.push(item) : console.log();
                                    }
                                })
                            } else if(item.level === 3){
                                getCheckedKeysSet.delete(item.id);
                                this.freightData.forEach(freightData => {
                                    freightData.children.forEach(freightDataChildren => {
                                        if (freightDataChildren.id === item.pid) {
                                            getCheckedKeysSet.delete(freightDataChildren.id);
                                            this.compareFreight(freightDataChildren.children, item.id) ?
                                                freightDataChildren.children.push(item) : console.log();
                                        }
                                    })
                                })
                            }
                        }
                        if(getCheckedKeysSet.size){
                            this.getKeysSetProvinces(Array.from(getCheckedKeysSet))
                        }else {
                            this.setTreeData()
                        }
                    })
            },
            getKeysSetProvinces(getCheckedKeysArray) {
                axios
                    .get('provinces', {
                        params: {
                            pagination: 1,
                            pageSize: 9999,
                            pid: ['in', getCheckedKeysArray.toString()],
                            sortBy: 'id',
                            orderBy: 'asc',
                        }
                    })
                    .then(res => res.data.data)
                    .then(res => {
                        let array = [];
                        array.push(...this.setFreightData(res));
                        array.length ? this.getKeysSetProvinces(array): this.setTreeData();
                    })
            },
            setFreightData(resItem_res){
                let array = [];
                for (let item of resItem_res){
                    item.children = [];
                    if(item.level === 1){
                        this.compareFreight(this.freightData, item.id) ? this.freightData.push(item): console.log();
                    } else if(item.level === 2){
                        array.push(item.id);
                        this.freightData.forEach(freightData => {
                            if (freightData.id === item.pid) {
                                this.compareFreight(freightData.children, item.id) ?
                                    freightData.children.push(item) : console.log();
                            }
                        })
                    } else if(item.level === 3){
                        this.freightData.forEach(freightData => {
                            freightData.children.forEach(freightDataChildren => {
                                if (freightDataChildren.id === item.pid) {
                                    this.compareFreight(freightDataChildren.children, item.id) ?
                                        freightDataChildren.children.push(item) : console.log();
                                }
                            })
                        })
                    }
                }
                return array;
            },
            setTreeData() {
                this.loading = false;
                this.treeData = JSON.parse(JSON.stringify(this.freightData))
            },
            compareFreight(data, id) {
                let bool = true;
                data.map(item => {
                    item.id === id ? bool = false : console.log();
                });
                return bool;
            }
        }
    }
</script>

<style scoped>
    .freight-dialog-content {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }
    .fy-tree{
        width: 300px;
        border: 1px solid #ebeef5;
    }
    .fy-tree_nav{
        background: #F6F6F6;
        height: 44px;
        border-bottom: 1px solid #ebeef5;
        line-height: 44px;
        text-align: center;
    }
    .fy-tree_content{
        height: 400px;
        overflow-y: auto;
    }
</style>
<style>
    .freight-dialog .el-dialog__header {
        background: #3F7DFF;
        text-align: center;
    }

    .freight-dialog .el-dialog__header span {
        color: white;
        text-align: center;
    }

    .freight-dialog .el-dialog__footer {
        background: #F6F6F6;
    }
</style>